package com.zzp.completablefuturedemo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureTest1 {

//    whenComplete执行当前任务的线程去执行该任务
//    whenCompleteAsync交给线程池
//    exceptionally处理异常情况
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            int i = 1 / 0;
            return 1024;
        }).whenComplete((t, s) -> {
            System.out.println("t:\t" + t);
            System.out.println("s:\t" + s);
        }).exceptionally(e -> {
            System.out.println("e:\t" + e);
            return 404;
        });

        //toString方法和CompletableFuture有冲突？
        System.out.println(future.get());
        Person person = new Person("1", 1);
//        System.out.println(person);

        Person p = new Person();
        CompletableFuture<Person> zhangsan = CompletableFuture.supplyAsync(() -> {
            p.setId(1);
            p.setName("zhangsan");
            return p;
        });
        zhangsan.thenAcceptAsync(i -> {
            System.out.println(i.getId());
            System.out.println(i.getName());
            System.out.println(i);
        });
    }
}

class Person {
    String name;
    int id;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Person() {
    }

    public Person(String name, int id) {
        this.name = name;
        this.id = id;
    }
}